package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //1. 从redis查询店铺信息
        List<String> cachedList = stringRedisTemplate.opsForList().range(CACHE_KEY, 0, -1);

        //2. 存在，直接返回
        if (cachedList != null && !cachedList.isEmpty()) {
            // 2.1.若 Redis 中存在该缓存，则直接返回
            ArrayList<ShopType> typeList = new ArrayList<>();
            for (String str : cachedList) {
                typeList.add(JSONUtil.toBean(str, ShopType.class));
            }

            return Result.ok(typeList);
        }

        //3. 不存在，查询数据库获得并写到redis中
        List<ShopType> typeList = query().orderByAsc("sort").list();
        if (typeList == null || typeList.isEmpty()) {
            Result.fail("数据库中没有店铺类型");
        }
        //saveToRedis
        for (ShopType shopType : typeList) {
            stringRedisTemplate.opsForList().rightPushAll(CACHE_KEY, JSONUtil.toJsonStr(shopType));
        }
        stringRedisTemplate.expire(CACHE_KEY, CACHE_SHOP_TTL, TimeUnit.HOURS);
        //4. 返回

        return Result.ok(typeList);
    }
}
